package ifgi.potwc.ipt.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * This class represents the app's database.
 * 
 * @author saschak.
 */
public class IptDatabase extends SQLiteOpenHelper
{
    // Database name & version
    public static final String DB_NAME = "ipt.db";
    private static final int DB_VERSION = 1;

    // Datastreams
    public static final String ACC = "acceleration";
    public static final String BRI = "brightness";
    public static final String HUM = "humidity";
    public static final String LAT = "latitude";
    public static final String LON = "longitude";
    public static final String TMP = "temperature";

    // Table column names
    public static final String ID = "_id";
    public static final String FEED_ID = "feed_id";
    public static final String UPLOADED = "uploaded";
    public static final String TIMESTAMP = "timestamp";

    // Table name tag
    public static final String TABLE_TAG = "_table";

    /**
     * Constructor.
     * 
     * @param _context
     */
    public IptDatabase(Context _context)
    {
	super(_context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
	// Create tables for all datastreams
	db.execSQL(sqlCreate(ACC));
	db.execSQL(sqlCreate(BRI));
	db.execSQL(sqlCreate(HUM));
	db.execSQL(sqlCreate(LAT));
	db.execSQL(sqlCreate(LON));
	db.execSQL(sqlCreate(TMP));
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
	// Drop all tables
	db.execSQL(sqlDrop(ACC));
	db.execSQL(sqlDrop(BRI));
	db.execSQL(sqlDrop(HUM));
	db.execSQL(sqlDrop(LAT));
	db.execSQL(sqlDrop(LON));
	db.execSQL(sqlDrop(TMP));

	// Call onCreate-method to re-create tables
	onCreate(db);
    }

    /**
     * Returns an SQL statement for creating a database table for the given
     * datastream.
     * 
     * @param _datastream
     * @return The SQL statement
     */
    public String sqlCreate(String _datastream)
    {
	return "CREATE TABLE " + _datastream + TABLE_TAG + " (" + ID
		+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + FEED_ID
		+ " TEXT NOT NULL, " + UPLOADED + " INTEGER, " + TIMESTAMP
		+ " TEXT NOT NULL, " + _datastream + " REAL" + ");";
    }

    /**
     * Returns an SQL statement to drop the table for the given datastream from
     * the database.
     * 
     * @param _tableName
     * @return The SQL statement
     */
    public String sqlDrop(String _datastream)
    {
	return "DROP TABLE IF EXISTS " + _datastream + TABLE_TAG;
    }
}